package com.sunfeng.jksj.p27;

import com.sunfeng.TimeUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author : 孙峰
 * @Description:
 * @Date : 2022/3/7  12:51
 */
@Slf4j(topic = "c.Demo01")
public class Demo01 {
}

class Account {
    private int balance;

    private final Lock lock = new ReentrantLock();

    void transfer(Account tar, int amt) {
        while (true) {
            if (this.lock.tryLock()) {
                try {

                    if (tar.lock.tryLock()) {
                        try {
                            this.balance -= amt;
                            tar.balance += amt;
                            // 增加了跳出循环
                            break;
                        } finally {
                            tar.lock.unlock();
                        }
                    }

                } finally {
                    this.lock.unlock();
                }
            }
            // 增加随机睡眠时间
            Random random = new Random();
            TimeUtils.sleepMicroseconds(random.nextInt(1000));
        }
    }
}

